package server

import (
	"fmt"
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
)

func SocketSever() {
	server := socketio.NewServer(nil)

	//OnConnect set a handler function f to handle open event for namespace.
	//连接成功
	server.OnConnect("/", func(sock socketio.Conn) error {

		fmt.Println("connect success!", sock.ID())
		return nil
	})

	//接收"bye"事件
	//OnEvent设置处理程序函数f以处理命名空间的事件
	server.OnEvent("/", "bye", func(sock socketio.Conn) string {
		last := sock.Context().(string)
		sock.Emit("bye", last)
		sock.Close()
		fmt.Println("============>", last)

		return last
	})

	server.OnEvent("/chat", "msg", func(sock socketio.Conn, msg string) string {
		sock.SetContext(msg)
		fmt.Println("====chat===>", msg)
		return "server1发送的：" + msg
	})

	server.OnEvent("/", "message", func(sock socketio.Conn, msg string) {
		log.Println("recv message: ", msg)
		sock.Emit("reply", "have "+msg)
		//return "server2发送的：" + msg
	})

	server.OnEvent("/", "authenticate", func(sock socketio.Conn, client_msg string) {
		numOfWorkers := 10
		numOfTasks := 10

		var done = make(chan bool, 1)
		go GetResult(done, sock)
		go Allocate(numOfTasks, client_msg)
		go CreateWorkerPool(numOfWorkers)
		<-done

	})

	server.OnError("/", func(sock socketio.Conn, err error) {
		log.Println("meet error:", err)
	})

	server.OnDisconnect("/", func(sock socketio.Conn, reason string) {
		log.Println("close connect: ", reason)
	})

	go func() {
		if err := server.Serve(); err != nil {
			log.Fatalf("socketio listen error: %s\n", err)
		}
	}()
	defer server.Close()

	//router.Use(GinMiddleware("http://localhost:3000"))dd
	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("../asset/")))

	//router.GET("/socket.io/", gin.WrapH(server))
	//router.StaticFS()
	log.Println("Server at localhost:8000...")
	if err := http.ListenAndServe(":8000", nil); err != nil {
		log.Fatal("http.ListenAndServe ", err)
	}
}
